package com.tangyuan.common.util;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.Date;

@Data
@Slf4j
public class PictureOSSUtils {
    private static String endpoint="oss-cn-qingdao.aliyuncs.com"; // 阿里云 OSS 外网或内网地址
    private static String accessKeyId="LTAI5tQZMYYEwFYBC8vYCkPR"; // 阿里云账号 AccessKeyId
    private static String accessKeySecret="FKqXvgNCC5ivMFLcqZHh0TXF7u0iyF"; // 阿里云账号 AccessKeySecret
    private static String bucketName = "shengtangfeng1"; // 存储空间名称


    public static String upload(String videoUrl){
        if(StrUtil.isEmpty(videoUrl)){
            log.error("上传OSS失败");
            return "";
        }
        //上传视频到阿里
        MultipartFile video = fileUrlConvertToMultipartFile(videoUrl);
        return upload(video, FileNameUtil.getPngName());
    }

    public static MultipartFile fileUrlConvertToMultipartFile(String imageUrl) {
        try {
            // 将在线图片地址转换为URL对象
            URL url = new URL(imageUrl);
            // 打开URL连接
            URLConnection connection = url.openConnection();
            // 转换为HttpURLConnection对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 获取输入流
            InputStream inputStream = httpURLConnection.getInputStream();
            // 读取输入流中的数据，并保存到字节数组中
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            // 将字节数组转换为字节数组
            byte[] bytes = byteArrayOutputStream.toByteArray();
            // 创建ByteArrayInputStream对象，将字节数组传递给它
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            // 创建MultipartFile对象，将ByteArrayInputStream对象作为构造函数的参数
            return new MockMultipartFile("file", "filename.jpg", "image/jpg", byteArrayInputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * base64类型的图片上传阿里云
     * @param base64Str base64
     * @return 阿里云地址
     */
    public static String  uploadBase64Image(String base64Str) {
        byte[] imageBytes = Base64.getDecoder().decode(base64Str);
        MockMultipartFile file = new MockMultipartFile("file", "filename.jpg", "image/jpg", imageBytes);
        return upload(file, FileNameUtil.getPngName());
    }

    public static String  upload(MultipartFile file, String objectKey) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectKey, file.getInputStream());

            // 设置ObjectMetadata
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("picture/png");
            metadata.setHeader("x-oss-force-download", false);
            putObjectRequest.setMetadata(metadata);
            // 设置文件访问权限，默认是私有读写
            ossClient.putObject(putObjectRequest);

            // 设置文件访问权限（可选）
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            // 获取上传后的文件URL
            return "https://" + bucketName + "." + endpoint + "/" + objectKey;
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            return null;
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }
    public static String uploadFileAndGetUrl( String bucketName, String objectName, File file) {

         String endpoint="oss-cn-qingdao.aliyuncs.com"; // 阿里云 OSS 外网或内网地址
         String accessKeyId="LTAI5tBWCaC4NC5B5ML5Poot"; // 阿里云账号 AccessKeyId
         String accessKeySecret="Th5HYspaDkPEODm1FV0BOsQem8qRg7"; // 阿里云账号 AccessKeySecret // 创建 OSSClient 对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String url = null;

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, file);

            // 生成文件的 URL 地址
            Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // URL 过期时间为 1 小时
            URL ossUrl = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            url = ossUrl.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭 OSSClient
            ossClient.shutdown();
        }

        return url;
    }

    public static void delOssFile(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        objectName =objectName.replaceAll("https://"+bucketName+"."+endpoint+"/", "");
        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            /**
             * objectName指文件目录地址，例如：空间名/文件地址
             * 例如：https://douyin-xjy.oss-cn-hangzhou.aliyuncs.com/douyin-xjy/hecheng/2023/04/20/e365a31b279e421a9fd295a0441dd92f.mp4
             * douyin-xjy：为设置的阿里云存储对象OSS空间名
             * objectName = douyin-xjy/hecheng/2023/04/20/e365a31b279e421a9fd295a0441dd92f.mp4
             */
            //https://shengtangfeng1.oss-cn-qingdao.aliyuncs.com/2024-04-28T09:11:41.316172740e0afcd9f39f5a06683.mp4
            ossClient.deleteObject(bucketName, objectName);

            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
